<template>
  <div class="alert-manager">
    <div class="dashboard-header">
      <div class="header-left">
        <div class="header-title">
          <el-icon><AlarmClock /></el-icon>
          <h1>告警中心</h1>
        </div>
        <div class="header-subtitle">实时监控系统状态，及时处理异常</div>
      </div>
      <div class="header-actions">
        <el-button 
          :class="['monitor-toggle-btn', alertMonitoringStatus ? 'is-active' : '']"
          @click="toggleAlertMonitoring">
          <el-icon><Bell /></el-icon>
          {{ alertMonitoringStatus ? '监控中' : '开启监控' }}
        </el-button>
        <el-button class="add-rule-btn" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新建规则
        </el-button>
      </div>
    </div>

    <!-- 监控状态卡片 -->
    <div class="status-cards">
      <div class="status-card total-alerts">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="card-data">
            <div class="card-value">{{ alertStatistics.total_alerts }}</div>
            <div class="card-label">总告警数</div>
          </div>
        </div>
      </div>
      <div class="status-card active-alerts">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><CircleCloseFilled /></el-icon>
          </div>
          <div class="card-data">
            <div class="card-value">{{ alertStatistics.active_alerts }}</div>
            <div class="card-label">活跃告警</div>
          </div>
        </div>
      </div>
      
      <div class="status-card resolved-alerts">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><CircleCheckFilled /></el-icon>
          </div>
          <div class="card-data">
            <div class="card-value">{{ alertStatistics.resolved_alerts }}</div>
            <div class="card-label">已解决</div>
          </div>
        </div>
      </div>
      
      <div class="status-card rules-count">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="card-data">
            <div class="card-value">{{ alertRules.length }}</div>
            <div class="card-label">告警规则</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 标签切换 -->
      <div class="content-tabs">
        <div 
          :class="['tab-item', activeTab === 'rules' ? 'active' : '']" 
          @click="activeTab = 'rules'">
          <el-icon><Document /></el-icon>
          告警规则
        </div>
        <div 
          :class="['tab-item', activeTab === 'history' ? 'active' : '']" 
          @click="activeTab = 'history'">
          <el-icon><Histogram /></el-icon>
          告警历史
        </div>
      </div>
      
      <!-- 规则列表 -->
      <div v-if="activeTab === 'rules'" class="content-panel">
        <div class="panel-header">
          <h2>规则列表</h2>
          <el-input
            v-model="ruleSearchKeyword"
            placeholder="搜索规则名称"
            prefix-icon="Search"
            clearable
            class="search-input"
          />
        </div>
        
        <el-table
          :data="filteredRules"
          v-loading="tableLoading"
          empty-text="暂无告警规则"
          class="data-table"
          row-class-name="table-row">
          
          <el-table-column label="规则名称" prop="name" min-width="180px">
            <template #default="scope">
              <div class="rule-name">
                <span class="rule-text">{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="监控指标" width="100">
            <template #default="scope">
              <el-tag size="small" effect="dark" class="metric-tag">
                {{ getMetricTypeText(scope.row.metric_type) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="条件" width="120">
            <template #default="scope">
              <span class="condition-text">
                {{ getConditionText(scope.row.condition) }} {{ scope.row.threshold }}{{ getUnitText(scope.row.metric_type) }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column label="严重程度" width="90">
            <template #default="scope">
              <div class="severity-badge" :class="'severity-' + scope.row.severity">
                {{ getSeverityText(scope.row.severity) }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="通知方式" width="120">
            <template #default="scope">
              <div class="notification-types">
                <el-tag 
                  v-for="type in scope.row.notification_types" 
                  :key="type" 
                  size="small"
                  class="notification-tag"
                  effect="plain">
                  {{ getNotificationTypeText(type) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="80">
            <template #default="scope">
              <el-switch 
                v-model="scope.row.is_enabled"
                @change="toggleRuleStatus(scope.row)"
                class="status-switch">
              </el-switch>
            </template>
          </el-table-column>
          
          <el-table-column label="创建时间" prop="create_time" width="160">
            <template #default="scope">
              <div class="time-display">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatTime(scope.row.create_time) }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="170" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="editRule(scope.row)" class="action-btn edit-btn">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="deleteRule(scope.row)" class="action-btn delete-btn">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 告警历史面板 -->
      <div v-if="activeTab === 'history'" class="content-panel">
        <div class="panel-header">
          <h2>告警历史</h2>
          <div class="filter-group">
            <el-select v-model="historyStatusFilter" placeholder="状态筛选" class="filter-select">
              <el-option label="全部" value="" />
              <el-option label="活跃" value="active" />
              <el-option label="已确认" value="acknowledged" />
              <el-option label="已解决" value="resolved" />
            </el-select>
            <el-date-picker
              v-model="historyDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="date-range"
            />
          </div>
        </div>
        
        <el-table
          :data="filteredHistory"
          v-loading="historyLoading"
          empty-text="暂无告警历史"
          class="data-table"
          row-class-name="table-row">
          
          <el-table-column label="告警名称" prop="rule_name" min-width="180">
            <template #default="scope">
              <div class="alert-name">{{ scope.row.rule_name }}</div>
            </template>
          </el-table-column>
          
          <el-table-column label="严重程度" width="90">
            <template #default="scope">
              <div class="severity-badge" :class="'severity-' + scope.row.severity">
                {{ getSeverityText(scope.row.severity) }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="触发值" width="120">
            <template #default="scope">
              <div class="trigger-value">
                {{ scope.row.triggered_value }}{{ getUnitText(scope.row.metric_type) }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <div class="status-badge" :class="'status-' + scope.row.status">
                {{ getAlertStatusText(scope.row.status) }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="触发时间" prop="triggered_at" width="160">
            <template #default="scope">
              <div class="time-display">
                <el-icon><Timer /></el-icon>
                <span>{{ formatTime(scope.row.triggered_at) }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="持续时间" width="120">
            <template #default="scope">
              <div class="duration">
                <el-icon><Clock /></el-icon>
                <span>{{ calculateDuration(scope.row.triggered_at, scope.row.resolved_at) }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === 'active'"
                type="success" 
                size="small" 
                class="action-btn confirm-btn"
                @click="acknowledgeAlert(scope.row)">
                <el-icon><Check /></el-icon>
                确认
              </el-button>
              <span v-else class="text-muted">已处理</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 创建/编辑告警规则对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingRule ? '编辑告警规则' : '创建告警规则'"
      width="600px"
      destroy-on-close
      class="custom-dialog"
      @close="resetForm">
      
      <el-form :model="ruleForm" :rules="formRules" ref="ruleFormRef" label-width="100px" class="rule-form">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        
        <el-form-item label="监控指标" prop="metric_type">
          <el-select v-model="ruleForm.metric_type" placeholder="请选择监控指标" class="full-width">
            <el-option label="平均响应时间" value="avg_response_time" />
            <el-option label="错误率" value="error_rate" />
            <el-option label="TPS" value="tps" />
            <el-option label="CPU使用率" value="cpu_usage" />
            <el-option label="内存使用率" value="memory_usage" />
            <el-option label="并发用户数" value="concurrent_users" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="告警条件" prop="condition">
          <div class="condition-group">
            <el-select v-model="ruleForm.condition" placeholder="条件" class="condition-select">
              <el-option label="大于" value="gt" />
              <el-option label="大于等于" value="gte" />
              <el-option label="小于" value="lt" />
              <el-option label="小于等于" value="lte" />
              <el-option label="等于" value="eq" />
            </el-select>
            <el-input-number 
              v-model="ruleForm.threshold" 
              :min="0"
              :precision="2"
              controls-position="right"
              class="threshold-input"
              placeholder="阈值">
            </el-input-number>
          </div>
        </el-form-item>
        
        <el-form-item label="严重程度" prop="severity">
          <div class="severity-options">
            <div 
              v-for="level in [
                {value: 'low', text: '低', color: '#67C23A', bg: '#E1F3D8'},
                {value: 'medium', text: '中', color: '#3b99e5', bg: '#ECF5FF'},
                {value: 'high', text: '高', color: '#E6A23C', bg: '#FDF6EC'},
                {value: 'critical', text: '紧急', color: '#F56C6C', bg: '#FEF0F0'}
              ]" 
              :key="level.value"
              :class="['severity-option-new', {'selected': ruleForm.severity === level.value}]"
              :style="{
                'border-color': ruleForm.severity === level.value ? level.color : '#DCDFE6',
                'color': ruleForm.severity === level.value ? level.color : '#606266',
                'background-color': ruleForm.severity === level.value ? level.bg : 'transparent'
              }"
              @click="ruleForm.severity = level.value">
              {{ level.text }}
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="通知方式" prop="notification_types">
          <div class="notification-options">
            <div 
              v-for="type in ['email', 'webhook', 'dingtalk', 'wechat']" 
              :key="type"
              :class="['notification-option', {'selected': ruleForm.notification_types.includes(type)}]"
              @click="toggleNotificationType(type)">
              <el-icon v-if="type === 'email'"><Message /></el-icon>
              <el-icon v-else-if="type === 'webhook'"><Connection /></el-icon>
              <el-icon v-else-if="type === 'dingtalk'"><ChatDotRound /></el-icon>
              <el-icon v-else-if="type === 'wechat'"><ChatRound /></el-icon>
              {{ getNotificationTypeText(type) }}
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="关联任务" prop="task_ids">
          <el-select
            v-model="ruleForm.task_ids"
            multiple
            placeholder="不选择则默认关联所有任务"
            class="full-width"
            @change="handleTaskSelectionChange"
            :loading="tasksLoading">
            <el-option
              v-for="task in performanceTasks"
              :key="task.id"
              :label="task.name"
              :value="task.id">
            </el-option>
            <template #empty>
              <div v-if="tasksLoading" class="loading-text">
                加载任务中...
              </div>
              <div v-else-if="performanceTasks.length === 0" class="empty-text">
                暂无任务数据
              </div>
            </template>
          </el-select>
          <div class="form-help-text">
            不选择任务则默认关联所有任务，编辑模式下可保持原有关联关系
          </div>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="ruleForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入规则描述" />
        </el-form-item>
        
        <el-form-item label="启用规则">
          <div class="toggle-switch">
            <span :class="['toggle-label', {'active': !ruleForm.is_enabled}]">禁用</span>
            <el-switch v-model="ruleForm.is_enabled" class="big-switch" />
            <span :class="['toggle-label', {'active': ruleForm.is_enabled}]">启用</span>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateDialog = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading" class="submit-btn">
            {{ editingRule ? '保存更改' : '创建规则' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Bell, Warning, CircleCloseFilled, CircleCheckFilled, Setting,
  Edit, Delete, Check, Calendar, Timer, Clock, Message, Connection,
  ChatDotRound, ChatRound, AlarmClock, Document, Histogram, Search
} from '@element-plus/icons-vue'

export default {
  name: 'AlertManager',
  components: {
    Plus, Bell, Warning, CircleCloseFilled, CircleCheckFilled, Setting,
    Edit, Delete, Check, Calendar, Timer, Clock, Message, Connection,
    ChatDotRound, ChatRound, AlarmClock, Document, Histogram, Search
  },
  props: {
    projectId: {
      type: [String, Number],
      required: true
    }
  },
  emits: ['alert-triggered', 'alert-acknowledged', 'alert-rule-created'],
  data() {
    return {
      activeTab: 'rules',
      alertRules: [],
      alertHistory: [],
      tableLoading: false,
      historyLoading: false,
      submitLoading: false,
      showCreateDialog: false,
      editingRule: null,
      alertMonitoringStatus: false,
      ruleSearchKeyword: '',
      historyStatusFilter: '',
      historyDateRange: null,
      refreshTimer: null,
      performanceTasks: [], // 性能任务列表
      tasksLoading: false, // 加载任务状态
      
      alertStatistics: {
        total_alerts: 0,
        active_alerts: 0,
        resolved_alerts: 0
      },
      
      ruleForm: {
        name: '',
        metric_type: '',
        condition: '',
        threshold: 0,
        severity: '',
        notification_types: [],
        description: '',
        is_enabled: true,
        task_ids: [] // 关联的任务ID列表
      },
      
      formRules: {
        name: [
          { required: true, message: '请输入规则名称', trigger: 'blur' }
        ],
        metric_type: [
          { required: true, message: '请选择监控指标', trigger: 'change' }
        ],
        condition: [
          { required: true, message: '请选择告警条件', trigger: 'change' }
        ],
        threshold: [
          { required: true, message: '请输入阈值', trigger: 'blur' },
          { type: 'number', message: '阈值必须是数字', trigger: 'blur' }
        ],
        severity: [
          { required: true, message: '请选择严重程度', trigger: 'change' }
        ],
        notification_types: [
          { required: true, message: '请选择通知方式', trigger: 'change' },
          { type: 'array', min: 1, message: '请至少选择一种通知方式', trigger: 'change' }
        ],
        task_ids: [
          // 删除必填验证，改为非必填
          { type: 'array', message: '请选择关联任务', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadAlertRules()
    this.loadAlertHistory()
    this.loadAlertStatus()
    this.loadPerformanceTasks() // 加载性能任务
    
    // 设置定时刷新
    this.refreshTimer = setInterval(() => {
      if (this.alertMonitoringStatus) {
        this.loadAlertHistory()
        this.loadAlertStatus()
      }
    }, 30000) // 每30秒刷新一次
  },
  beforeUnmount() {
    // 清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  computed: {
    // 过滤后的规则列表
    filteredRules() {
      if (!this.ruleSearchKeyword) {
        return this.alertRules;
      }
      const keyword = this.ruleSearchKeyword.toLowerCase();
      return this.alertRules.filter(rule => 
        rule.name.toLowerCase().includes(keyword)
      );
    },
    
    // 过滤后的历史列表
    filteredHistory() {
      let result = this.alertHistory;
      
      // 状态过滤
      if (this.historyStatusFilter) {
        result = result.filter(item => item.status === this.historyStatusFilter);
      }
      
      // 日期范围过滤
      if (this.historyDateRange && this.historyDateRange.length === 2) {
        const startDate = new Date(this.historyDateRange[0]);
        const endDate = new Date(this.historyDateRange[1]);
        endDate.setHours(23, 59, 59, 999); // 设置为当天结束
        
        result = result.filter(item => {
          const triggerDate = new Date(item.triggered_at);
          return triggerDate >= startDate && triggerDate <= endDate;
        });
      }
      
      return result;
    }
  },
  methods: {
    // 切换通知类型
    toggleNotificationType(type) {
      const index = this.ruleForm.notification_types.indexOf(type);
      if (index > -1) {
        this.ruleForm.notification_types.splice(index, 1);
      } else {
        this.ruleForm.notification_types.push(type);
      }
    },

    // 处理任务选择变化
    handleTaskSelectionChange(value) {
      this.ruleForm.task_ids = value;
      console.log('已选择任务:', value);
    },
    
    // 加载告警规则
    async loadAlertRules() {
      this.tableLoading = true
      try {
        console.log('正在加载告警规则，项目ID:', this.projectId)
        const response = await this.$api.getAlertRules({ project_id: this.projectId })
        
        if (response.status === 200) {
          this.alertRules = response.data || []
          console.log('成功加载告警规则:', this.alertRules.length, '条记录')
        }
      } catch (error) {
        console.error('加载告警规则失败:', error)
        if (error.response?.status === 404) {
          ElMessage.warning('告警功能暂未配置，请联系管理员')
        } else {
          ElMessage.error('加载告警规则失败: ' + (error.response?.data?.message || error.message || '网络错误'))
        }
        this.alertRules = []
      } finally {
        this.tableLoading = false
      }
    },
    
    // 加载告警历史
    async loadAlertHistory() {
      this.historyLoading = true
      try {
        console.log('正在加载告警历史，项目ID:', this.projectId)
        const response = await this.$api.getAlertHistory({ project_id: this.projectId })
        
        if (response.status === 200) {
          const newAlertHistory = response.data || []
          console.log('成功加载告警历史:', newAlertHistory.length, '条记录')
          
          // 检查是否有新的告警
          this._checkForNewAlerts(this.alertHistory, newAlertHistory)
          
          // 更新告警历史
          this.alertHistory = newAlertHistory
        }
      } catch (error) {
        console.error('加载告警历史失败:', error)
        if (error.response?.status === 404) {
          ElMessage.warning('告警历史暂未配置，请联系管理员')
        } else {
          ElMessage.error('加载告警历史失败: ' + (error.response?.data?.message || error.message || '网络错误'))
        }
        this.alertHistory = []
      } finally {
        this.historyLoading = false
      }
    },
    
    // 加载告警状态
    async loadAlertStatus() {
      try {
        const response = await this.$api.getAlertStatus({ project_id: this.projectId })
        
        if (response.status === 200) {
          const statistics = response.data.statistics || {}
          this.alertStatistics = {
            total_alerts: statistics.total || 0,
            active_alerts: statistics.active || 0,
            resolved_alerts: statistics.resolved || 0
          }
          this.alertMonitoringStatus = response.data.monitoring_status || false
          console.log('成功加载告警状态:', this.alertStatistics, '监控状态:', this.alertMonitoringStatus)
        }
      } catch (error) {
        console.error('加载告警状态失败:', error)
        // 设置默认值
        this.alertStatistics = {
          total_alerts: 0,
          active_alerts: 0,
          resolved_alerts: 0
        }
        this.alertMonitoringStatus = false
      }
    },

    // 加载性能任务
    async loadPerformanceTasks() {
      this.tasksLoading = true;
      try {
        // 获取所有任务，不限于当前项目
        const response = await this.$api.getPerformanceTasks();
        if (response.status === 200) {
          // 处理分页和非分页的数据结构
          let tasks = response.data;
          if (response.data && response.data.results) {
            tasks = response.data.results; // 分页结构
          }
          
          // 将任务数据转换为选项格式，确保显示任务名称
          this.performanceTasks = tasks.map(task => ({
            id: task.id,
            name: task.taskName || `任务 #${task.id}`
          }));
          
          console.log('成功加载性能任务:', this.performanceTasks.length, '条记录');
        }
      } catch (error) {
        console.error('加载性能任务失败:', error);
        ElMessage.error('加载性能任务失败: ' + (error.response?.data?.message || error.message || '网络错误'));
        this.performanceTasks = [];
      } finally {
        this.tasksLoading = false;
      }
    },
    
    // 切换告警监控状态
    async toggleAlertMonitoring() {
      try {
        let response
        if (this.alertMonitoringStatus) {
          console.log('正在停止告警监控...')
          response = await this.$api.stopAlertMonitoring()
        } else {
          console.log('正在启动告警监控...')
          response = await this.$api.startAlertMonitoring()
        }
        
        if (response.status === 200) {
          this.alertMonitoringStatus = !this.alertMonitoringStatus
          ElMessage.success(this.alertMonitoringStatus ? '告警监控已启动' : '告警监控已停止')
          
          // 刷新告警状态
          this.loadAlertStatus()
        }
      } catch (error) {
        console.error('切换监控状态失败:', error)
        ElMessage.error('切换监控状态失败: ' + (error.response?.data?.message || error.message || '网络错误'))
      }
    },
    
    // 切换规则状态
    async toggleRuleStatus(rule) {
      try {
        console.log('切换规则状态:', rule.id, rule.is_enabled)
        
        // 由于后端没有完整实现updateAlertRule，我们只做前端状态更新
        ElMessage.success(rule.is_enabled ? '规则已启用' : '规则已禁用')
        
        // 模拟API调用
        const originalStatus = rule.is_enabled
        try {
          const response = await this.$api.updateAlertRule(rule.id, { is_enabled: rule.is_enabled })
          if (response.status !== 200 && response.status !== 201) {
            throw new Error('状态更新失败')
          }
        } catch (error) {
          // 如果API调用失败，恢复原始状态
          rule.is_enabled = !rule.is_enabled
          throw error
        }
      } catch (error) {
        console.error('更新规则状态失败:', error)
        ElMessage.error('更新规则状态失败: ' + (error.response?.data?.message || error.message || '网络错误'))
      }
    },
    
    // 编辑规则
    editRule(rule) {
      this.editingRule = rule
      // 深拷贝规则数据，避免直接修改原始数据
      this.ruleForm = JSON.parse(JSON.stringify(rule))
      
      // 确保任务IDs是数组格式
      if (typeof this.ruleForm.task_ids === 'string') {
        try {
          this.ruleForm.task_ids = JSON.parse(this.ruleForm.task_ids);
        } catch (e) {
          console.error('解析任务ID失败:', e);
          this.ruleForm.task_ids = [];
        }
      }
      
      // 如果任务ID为null，设置为空数组
      if (!this.ruleForm.task_ids) {
        this.ruleForm.task_ids = [];
      }
      
      // 显示编辑对话框
      this.showCreateDialog = true
    },
    
    // 删除规则
    async deleteRule(rule) {
      try {
        await ElMessageBox.confirm(
          `确定要删除告警规则 "${rule.name}" 吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        console.log('正在删除规则:', rule.id)
        const response = await this.$api.deleteAlertRule(rule.id)
        
        if (response.status === 204 || response.status === 200) {
          ElMessage.success('删除成功')
          
          // 手动从列表中移除该规则
          this.alertRules = this.alertRules.filter(r => r.id !== rule.id)
          
          // 更新统计数据
          if (this.alertStatistics.total_alerts > 0) {
            this.alertStatistics.total_alerts -= 1
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除规则失败:', error)
          ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message || '网络错误'))
        }
      }
    },
    
    // 确认告警
    async acknowledgeAlert(alert) {
      try {
        console.log('正在确认告警:', alert.id)
        const response = await this.$api.acknowledgeAlert({
          alert_id: alert.id,
          acknowledger: 'current_user'
        })
        
        if (response.status === 200) {
          ElMessage.success('告警已确认')
          // 刷新告警列表和状态
          this.loadAlertHistory()
          this.loadAlertStatus()
          
          // 触发事件，通知父组件告警已确认
          this.$emit('alert-acknowledged', alert)
        }
      } catch (error) {
        console.error('确认告警失败:', error)
        ElMessage.error('确认告警失败: ' + (error.response?.data?.message || error.message || '网络错误'))
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        const valid = await this.$refs.ruleFormRef.validate()
        if (!valid) return
        
        this.submitLoading = true
        
        // 构建参数对象
        const params = {
          ...this.ruleForm,
          project_id: this.projectId,
          // 添加默认的通知配置，避免后端报错
          notification_config: JSON.stringify({
            email: {
              recipients: []
            },
            webhook: {
              url: ""
            }
          })
        }
        
        // 确保通知类型始终是数组
        if (!params.notification_types || !Array.isArray(params.notification_types)) {
          params.notification_types = []
        }
        
        // 确保通知类型至少有一项
        if (params.notification_types.length === 0) {
          params.notification_types.push('email')
        }

        // 确保任务ID始终是数组
        if (!params.task_ids || !Array.isArray(params.task_ids)) {
          params.task_ids = [];
        }

        // 处理任务ID，空数组代表关联所有任务
        if (params.task_ids.length === 0) {
          // 添加一个特殊标记，表示关联所有任务
          params.link_all_tasks = true;
          console.log('未选择任务，将关联所有任务');
        } else {
          params.link_all_tasks = false;
        }
        
        // 调试日志：查看发送的数据
        console.log('提交告警规则数据:', params)
        
        let response
        if (this.editingRule) {
          response = await this.$api.updateAlertRule(this.editingRule.id, params)
        } else {
          response = await this.$api.addAlertRule(params)
        }
        
        if (response.status === 200 || response.status === 201) {
          ElMessage.success(this.editingRule ? '更新成功' : '创建成功')
          this.showCreateDialog = false
          
          // 手动更新规则列表
          if (this.editingRule) {
            // 更新现有规则
            const index = this.alertRules.findIndex(r => r.id === this.editingRule.id)
            if (index !== -1) {
              // 使用新规则替换旧规则
              const updatedRule = response.data?.rule || {
                ...params,
                id: this.editingRule.id,
                create_time: this.editingRule.create_time
              }
              // Vue 3中直接赋值即可
              this.alertRules[index] = updatedRule
            }
          } else {
            // 添加新规则
            const newRule = response.data?.rule || {
              ...params,
              id: Date.now(), // 生成临时ID
              create_time: new Date().toISOString()
            }
            this.alertRules.unshift(newRule)
            
            // 更新统计数据
            this.alertStatistics.total_alerts += 1
            
            // 如果是新建规则并创建成功，触发事件通知父组件
            this.$emit('alert-rule-created', newRule)
          }
          
          // 刷新规则列表
          this.loadAlertRules()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message || '网络错误'))
      } finally {
        this.submitLoading = false
      }
    },
    
    // 重置表单
    resetForm() {
      this.editingRule = null
      this.ruleForm = {
        name: '',
        metric_type: '',
        condition: '',
        threshold: 0,
        severity: '',
        notification_types: [],
        description: '',
        is_enabled: true,
        task_ids: []
      }
      this.$refs.ruleFormRef?.resetFields()
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      return new Date(time).toLocaleString()
    },
    
    // 计算持续时间
    calculateDuration(startTime, endTime) {
      if (!startTime) return '-'
      const start = new Date(startTime)
      const end = endTime ? new Date(endTime) : new Date()
      const diff = Math.floor((end - start) / 1000)
      
      if (diff < 60) return `${diff}秒`
      if (diff < 3600) return `${Math.floor(diff / 60)}分钟`
      return `${Math.floor(diff / 3600)}小时`
    },
    
    // 获取指标类型文本
    getMetricTypeText(type) {
      const types = {
        avg_response_time: '响应时间',
        error_rate: '错误率',
        tps: 'TPS',
        cpu_usage: 'CPU',
        memory_usage: '内存',
        concurrent_users: '并发数'
      }
      return types[type] || type
    },
    
    // 获取条件文本
    getConditionText(condition) {
      const conditions = {
        gt: '>',
        gte: '≥',
        lt: '<',
        lte: '≤',
        eq: '='
      }
      return conditions[condition] || condition
    },
    
    // 获取单位文本
    getUnitText(metricType) {
      const units = {
        avg_response_time: 'ms',
        error_rate: '%',
        tps: '',
        cpu_usage: '%',
        memory_usage: '%',
        concurrent_users: ''
      }
      return units[metricType] || ''
    },
    
    // 获取严重程度类型
    getSeverityType(severity) {
      const types = {
        low: 'info',
        medium: 'warning',
        high: 'danger',
        critical: 'danger'
      }
      return types[severity] || 'info'
    },
    
    // 获取严重程度文本
    getSeverityText(severity) {
      const texts = {
        low: '低',
        medium: '中',
        high: '高',
        critical: '紧急'
      }
      return texts[severity] || severity
    },
    
    // 获取通知类型文本
    getNotificationTypeText(type) {
      const types = {
        email: '邮件',
        webhook: 'Webhook',
        dingtalk: '钉钉',
        wechat: '微信'
      }
      return types[type] || type
    },
    
    // 获取告警状态类型
    getAlertStatusType(status) {
      const types = {
        active: 'danger',
        acknowledged: 'warning',
        resolved: 'success'
      }
      return types[status] || 'info'
    },
    
    // 获取告警状态文本
    getAlertStatusText(status) {
      const texts = {
        active: '活跃',
        acknowledged: '已确认',
        resolved: '已解决'
      }
      return texts[status] || status
    },
    
    // 检查新的告警
    _checkForNewAlerts(oldAlerts, newAlerts) {
      if (!oldAlerts || oldAlerts.length === 0) return
      
      // 查找新添加的active告警
      const newActiveAlerts = newAlerts.filter(alert => 
        alert.status === 'active' && 
        !oldAlerts.some(oldAlert => oldAlert.id === alert.id)
      )
      
      // 触发告警事件
      newActiveAlerts.forEach(alert => {
        console.log('检测到新的告警:', alert)
        this.$emit('alert-triggered', alert)
      })
    },
    
  }
}
</script>

<style scoped>
/* 全局样式 */
.alert-manager {
  padding: 20px;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  color: #333;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

/* 头部样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.header-title {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.header-title h1 {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 0 10px;
  color: #303133;
}

.header-title .el-icon {
  font-size: 24px;
  color: #409EFF;
}

.header-subtitle {
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.monitor-toggle-btn {
  background: #f0f2f5;
  border: none;
  color: #606266;
  padding: 10px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.monitor-toggle-btn.is-active {
  background: #ecf5ff;
  color: #409EFF;
}

.monitor-toggle-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.add-rule-btn {
  background: #409EFF;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-rule-btn:hover {
  background: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 状态卡片样式 */
.status-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.status-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  overflow: hidden;
  cursor: pointer;
}

.status-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.status-card.total-alerts {
  border-top: 4px solid #E6A23C;
}

.status-card.active-alerts {
  border-top: 4px solid #F56C6C;
}

.status-card.resolved-alerts {
  border-top: 4px solid #67C23A;
}

.status-card.rules-count {
  border-top: 4px solid #409EFF;
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 16px;
  transition: all 0.3s ease;
}

.total-alerts .card-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.active-alerts .card-icon {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.resolved-alerts .card-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.rules-count .card-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.status-card:hover .card-icon {
  transform: scale(1.1) rotate(5deg);
}

.card-data {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1.2;
  color: #303133;
  margin-bottom: 6px;
}

.card-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

/* 主内容区域 */
.main-content {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 标签切换 */
.content-tabs {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
}

.tab-item {
  padding: 16px 24px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  color: #606266;
  border-bottom: 2px solid transparent;
}

.tab-item:hover {
  color: #409EFF;
}

.tab-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  font-weight: 500;
}

/* 内容面板 */
.content-panel {
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h2 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

.search-input {
  width: 240px;
}

.filter-group {
  display: flex;
  gap: 12px;
}

.filter-select {
  width: 120px;
}

.date-range {
  width: 320px;
}

/* 表格样式 */
.data-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.table-row {
  transition: all 0.2s ease;
}

.table-row:hover {
  background-color: #f5f7fa;
}

/* 表格内容样式 */
.rule-name {
  font-weight: 500;
  color: #303133;
}

.metric-tag {
  font-weight: 500;
}

.condition-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #606266;
  background: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
}

.severity-badge {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  text-align: center;
}

.severity-low {
  background-color: #e1f3d8;
  color: #67C23A;
}

.severity-medium {
  background-color: #ecf5ff;
  color: #3b99e5;
}

.severity-high {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.severity-critical {
  background-color: #fef0f0;
  color: #F56C6C;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.status-active {
  background-color: #fef0f0;
  color: #F56C6C;
}

.status-acknowledged {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.status-resolved {
  background-color: #e1f3d8;
  color: #67C23A;
}

.notification-types {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.notification-tag {
  background: #f0f2f5;
  border: none;
  color: #606266;
}

.time-display, .duration {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  border: none;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.edit-btn {
  background: #ecf5ff;
  color: #409EFF;
}

.delete-btn {
  background: #fef0f0;
  color: #F56C6C;
}

.confirm-btn {
  background: #f0f9eb;
  color: #67C23A;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.text-muted {
  color: #909399;
  font-style: italic;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.rule-form {
  padding: 20px 0;
}

.full-width {
  width: 100%;
}

.condition-group {
  display: flex;
  gap: 12px;
}

.condition-select {
  width: 120px;
}

.threshold-input {
  flex: 1;
}

.severity-options {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.severity-option-new {
  flex: 1;
  padding: 16px 0;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.severity-option-new:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}

.severity-option-new::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background-color: currentColor;
  opacity: 0.6;
}

.severity-option-new.selected {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  border-width: 3px;
}

.notification-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.notification-option {
  padding: 8px 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.notification-option.selected {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

.toggle-switch {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toggle-label {
  color: #909399;
  transition: all 0.2s ease;
}

.toggle-label.active {
  color: #303133;
  font-weight: 500;
}

.big-switch {
  transform: scale(1.2);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

.cancel-btn {
  border: none;
  background: #f0f2f5;
}

.submit-btn {
  border: none;
  background: #409EFF;
  padding: 10px 24px;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .status-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .status-cards {
    grid-template-columns: 1fr;
  }
  
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-input,
  .filter-select,
  .date-range {
    width: 100%;
  }
  
  .filter-group {
    width: 100%;
    flex-direction: column;
  }
  
  .severity-options,
  .notification-options {
    flex-direction: column;
  }
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  font-style: italic;
}

.loading-text, .empty-text {
  text-align: center;
  padding: 12px 0;
  color: #909399;
  font-size: 14px;
}

.loading-text {
  color: #409EFF;
}
</style>